package com.framework.plugin.xmlsql.tag;

import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

public class ForeachTag extends DefaultTag {
	
	private String collection;
	private String items;
	private String open;
	private String close;
	private String separator;
	private Object obj;
	public String getCollection() {
		return collection;
	}
	public void setCollection(String collection) {
		this.collection = collection;
	}
	public String getItems() {
		return items;
	}
	public void setItems(String items) {
		this.items = items;
	}
	public String getOpen() {
		return open;
	}
	public void setOpen(String open) {
		this.open = open;
	}
	public String getClose() {
		return close;
	}
	public void setClose(String close) {
		this.close = close;
	}
	public String getSeparator() {
		return separator;
	}
	public void setSeparator(String separator) {
		this.separator = separator;
	}
	public Object getObj() {
		return obj;
	}
	public void setObj(Object obj) {
		this.obj = obj;
	}
	public ForeachTag(Map<String, Object> map) {
		super.setMap(map);
	}
	@SuppressWarnings("rawtypes")
	@Override
	public String createSql(String text) {
		if(obj!=null) {
			int size = 0;
			if("list".equals(collection)) {
    			size = ((List)obj).size();
    		} else if("array".equals(collection)) {
    			size = ((Object[])obj).length;
    		}
			String[] ss = new String[size];
			for(int i=0;i<size;i++) {
				ss[i] = text;
			}
			return open+StringUtils.join(ss, separator)+close;
		}
		return open+close;
	}
	@Override
	public void prepare() {
		collection = attr("collection");
    	items = attr("items");
    	open = attr("open");
    	close = attr("close");
    	separator = attr("separator");
    	obj = getMap().get(items);
	}

}
